<?php

declare(strict_types=1);

namespace App\Chat\Service;

use App\Chat\Constant\TalkEventConstant;
use App\CustHub\Mapper\ChTalkFollowUpTaskMapper;
use App\CustHub\Model\ChContact;
use App\CustHub\Model\ChRoom;
use App\CustHub\Model\ChTalkFollowUpTask;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;

class TalkFollowUpTaskService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected SocketClientService $clientService;

    public function __construct(ChTalkFollowUpTaskMapper $mapper)
    {
        $this->mapper = $mapper;
    }


    /**
     * 设置下次跟进时间
     * @param array $params
     * @return bool
     */

    public function setNextFollowUpTime(array $params): bool
    {
        if(empty($params['id'])){
            throw new NormalStatusException('参数错误');
        }

        $info = ChTalkFollowUpTask::query()
            ->where('id',$params['id'])
            ->first();

        if(empty($info)){
            return false;
        }

        $nextFollowUpTime = Carbon::parse($info->time)->addMinutes(5)->toDateTimeString();
        $info->time = $nextFollowUpTime;
        $info->status = 0;
        $info->is_next = 1;
        return $info->save();
    }

    public function cancel(array $params): bool
    {
        $id = $params['id'];
        $info = ChTalkFollowUpTask::query()
            ->where('id',$id)
            ->first();

        if(empty($info) || $info->status != 0){
            return false;
        }

        $info->status = 2;
        return $info->save();
    }


    public function getFollowUpTasks(): void
    {
        $list = ChTalkFollowUpTask::query()
            ->with(['session'])
            ->where('time','<=',Carbon::now()->toDateTimeString())
            ->where('status',0)
            ->get();

        foreach ($list as $item){
            $item->status = 1;
            $item->save();
            if(!empty($item->session)){
                $fds = $this->clientService->findUserFds($item['uid']);
                if(empty($fds)){
                    continue;
                }
                $session = $item->session;
                if($session->talk_type == 1){
                    //私聊
                    $contactInfo = ChContact::query()
                        ->where('robot_id',$session->robot_id)
                        ->where('user_id',$session->receiver_id)
                        ->first();
                    $nickname = $contactInfo->nickname;
                    $avatar = $contactInfo->avatar;
                }else{
                    //群聊
                    $roomInfo = ChRoom::query()
                        ->where('room_wxid',$session->receiver_id)
                        ->whereHas('robots',function ($query) use ($session){
                            $query->where('robot_id',$session->robot_id);
                        })
                        ->first();
                    $nickname = $roomInfo->room_name;
                    $avatar = $roomInfo->room_avatar_url;
                }

                $this->push($fds,$this->toJson(TalkEventConstant::EVENT_TALK_FOLLOW_UP, [
                    'id' => $session->id,
                    'type'       => $item->type,
                    'time'       => $item->time,
                    'content'    => $item->content,
                    'nickname'   => $nickname,
                    'avatar'     => $avatar,
                    'is_next'    => $item->is_next
                ]));

            }
        }
    }

    private function toJson(string $event, array $data): string
    {
        return json_encode(["event" => $event, "content" => $data]);
    }

    private function push(array $fds, string $message): void
    {
        $server = server();
        foreach ($fds as $fd) {
            $server->exist(intval($fd)) && $server->push(intval($fd), $message);
        }
    }
}